import { reactive } from 'vue'

export default {
  props: {
    config: {
      type: Object
    },
    init: {
      type: Object
    }
  },
  emits: ['submitForm'],
  setup(props, context) {
    // 表单配置
    const { title, formItems } = props.config
    // 表单回显
    let formData = reactive(props.init)

    // 渲染表单元素
    const renderEle = (item) => {
      switch (item.type) {
        case 'input':
          return <el-input type={item.inputType} placeholder={item.placeholder} v-model={formData[item.key]}></el-input>
        case 'select':
          return <el-select v-model={formData[item.key]}>
            {item.options.map(opt => (
              <el-option label={opt.label} value={opt.value}></el-option>
            ))}
          </el-select>
        case 'number':
          return <el-input-number min={0} type={item.inputType} v-model={formData[item.key]} controls-position="right"></el-input-number>
        case 'radio':
          return <el-radio-group v-model={formData[item.key]}>
            {item.options.map(opt => (
              <el-radio value={opt.value}>{opt.label}</el-radio>
            ))}
          </el-radio-group>
        case 'checkbox':
          return <el-checkbox-group v-model={formData[item.key]}>
            {item.options.map(opt => (
              <el-checkbox label={opt.value}>{opt.label}</el-checkbox>
            ))}
          </el-checkbox-group>
        case 'date':
          return <el-date-picker v-model={formData[item.key]}
                                 type="date"
                                 placeholder="请选择时间"/>
      }
    }
    // 渲染列
    const renderColumn = (cols) => {
      return cols.map(col => (
        <el-col md={col.colspan}>
          <el-form-item label={col.label}>
            {renderEle(col)}
          </el-form-item>
        </el-col>
      ))
    }
    // 渲染行
    const renderRows = (rows) => {
      return rows.map(row => (
        <el-row>
          {renderColumn(row)}
        </el-row>
      ))
    }
    // 提交
    const submit = () => {
      console.log(formData)
      context.emit('submitForm', formData)
    }
    return () => (<>
      <el-button type="primary" onClick={submit}>提交</el-button>
      <el-form ref={'form'} label-width="80px">
        {formItems && renderRows(formItems)}
      </el-form>
    </>)
  }
}
